/*
 * Servhandler.java
 * provide basic outputhtml function and validation functions
 * 
 *  author: yanggang@kingsoft.com, wenjiesha.victor@gmail.com
 * 
 * */

package wps.servicebus;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mortbay.jetty.Request;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.AbstractHandler;

public abstract class ServHandler extends AbstractHandler
{
	public static class HandleTest extends ServHandler
	{
		@Override
		public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
			throws IOException, ServletException
		{
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    String tm = df.format(new Date()); 	
			
			OutputHtml(response, "Timestamp: " + tm);
			((Request)request).setHandled(true);
		}
	}
	
	protected void OutputHtml(HttpServletResponse response, String content) throws IOException, ServletException
	{
		byte[] contentBytes = content.getBytes("UTF-8");
	
		response.setStatus(200);
		response.setContentLength(contentBytes.length);
		
		OutputStream os = response.getOutputStream();
		os.write(contentBytes);
		os.flush();
	}
	
	protected boolean validate(Server server, HttpServletRequest request){
		if(server.getAttribute("controllerAddr") == null
				|| server.getAttribute("controllerPort") == null
				|| !((String)server.getAttribute("controllerAddr")).equals(request.getRemoteAddr())){
			return false;
		}
		return true;
	}
	
	protected boolean isControllerAvailable(Server server){
		if(server.getAttribute("controllerAddr") == null
				|| server.getAttribute("controllerPort") == null){
			return false;
		}
		return true;
	}
}
